package com.aruba.xfermodeapplication;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Xfermode;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * 橡皮擦效果
 */
public class RubberView extends View {
    private Bitmap bitmapSrc;
    //path的paint
    private Paint mPathPaint = new Paint();
    private Paint mPaint = new Paint();
    private Bitmap bitmapDst;
    //手势轨迹
    private Path path = new Path();
    //目标画布
    private  Canvas canvasDst;

    public RubberView(Context context) {
        this(context, null);
    }

    public RubberView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RubberView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setLayerType(LAYER_TYPE_SOFTWARE,null);
        
        bitmapSrc = BitmapFactory.decodeResource(getResources(), R.mipmap.xyjy6);
        
        //利用SRC_OUT使用透明的白底图片
        Bitmap.Config config = Bitmap.Config.ARGB_8888;
        bitmapDst = Bitmap.createBitmap(bitmapSrc.getWidth(), bitmapSrc.getHeight(), config);
        canvasDst = new Canvas(bitmapDst);
        
        //利用SRC_OUT使用不透明的颜色来描绘手势移动
        mPathPaint.setColor(Color.WHITE);
        //橡皮擦大小
        mPathPaint.setStrokeWidth(30);
        mPathPaint.setStyle(Paint.Style.STROKE);
        mPathPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                path.moveTo(event.getX(),event.getY());
                postInvalidate();
                return true;
            case MotionEvent.ACTION_MOVE:
                path.lineTo(event.getX(),event.getY());
                postInvalidate();
                break;
        }
        
        return false;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //在目标画布上画手势轨迹
        canvasDst.drawPath(path,mPathPaint);
        canvas.drawBitmap(bitmapDst,0,0, mPaint);
        
        Xfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT);
        mPaint.setXfermode(xfermode);
        canvas.drawBitmap(bitmapSrc, 0, 0, mPaint);
        mPaint.setXfermode(null);
    }
}
